<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    pageContext.setAttribute("root", request.getContextPath());
%>
<html>
<head>
    <title>查询所有员工</title>
    <script type="text/javascript" src="${root}/static/js/jquery.min.js"></script>
    <link href="${root}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${root}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Modal -->
<div class="modal fade" id="insertemp" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="insertemps">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">name</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" name="name" id="inputname" placeholder="name">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" name="email" id="inputemail" placeholder="Email">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-8">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="inlineRadio1" value="男" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="inlineRadio2" value="女"> 女
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">depname</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="idtodepid" id="dep">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="save">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 修改 -->
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="edits">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">name</label>
                        <div class="col-sm-8">
                            <p class="form-control-static" name="name" id="editname"></p>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" name="email" id="editemail" placeholder="Email">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-8">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="editRadio1" value="男"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="editRadio2" value="女"> 女
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">depname</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="idtodepid" id="editdep">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="editsave">保存</button>
            </div>
        </div>
    </div>
</div>


<%--错误--%>
<div class="modal fade bs-example-modal-sm" id="error" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            插入失败！
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>CRUD</h1>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 col-md-offset-10">
            <button class="btn btn-primary" id="insert">新增</button>
            <button class="btn btn-danger" id="delall">删除</button>
        </div>
    </div>
    <div class="row">
        <table class="table" id="emps">
            <thead>
            <tr>
                <th>
                    <input type="checkbox" id="checkall">
                </th>
                <th>id</th>
                <th>name</th>
                <th>gender</th>
                <th>email</th>
                <th>dep</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

    </div>
    <div class="row">
        <div class="col-md-6" id="pageinfo">
        </div>
        <div class="col-md-6" id="pagenav">
        </div>
    </div>
</div>
<script>
    var total;
    var id;
    var currentpage;
    $(document).ready(function () {
        $.ajax({
            url: "${root}/emps",
            data: "pn=1",
            type: "GET",
            success: function (data) {
                total = data.extend.pageemps.total;
                buildtable(data);
                buildpageinfo(data);
                buildpagenav(data);
            }
        });
    });

    function buildtable(data) {
        $("#emps tbody").empty();
        var empsdata = data.extend.pageemps.list;
        $.each(empsdata, function (index, item) {
            var checkbox = $("<td><input type='checkbox' class='checkitems'/></d>")
                .attr("value", item.id);
            var idtd = $("<td></td>").append(item.id);
            var nametd = $("<td></td>").append(item.name);
            var gendertd = $("<td></td>").append(item.gender);
            var emailtd = $("<td></td>").append(item.email);
            var deptd = $("<td></td>").append(item.dep.depname);
            var editbtn = $("<button></button>").addClass("btn btn-primary btn-sm editbtn").append("编辑")
                .attr("value", item.id);
            var delbtn = $("<button></button>").addClass("btn btn-danger btn-sm delbtn").append("删除")
                .attr("value", item.id);
            $("<tr></tr>")
                .append(checkbox)
                .append(idtd)
                .append(nametd)
                .append(gendertd)
                .append(emailtd)
                .append(deptd)
                .append(editbtn)
                .append("&nbsp;&nbsp;")
                .append(delbtn)
                .appendTo("#emps tbody");
        });
    }

    function buildpageinfo(data) {
        $("#pageinfo").empty();
        currentpage = data.extend.pageemps.pageNum;
        $("#pageinfo").append("当前第" + data.extend.pageemps.pageNum + "页，" +
            "总共" + data.extend.pageemps.pages + "页，总记录数有" + data.extend.pageemps.total + "条。")
    }

    function buildpagenav(data) {
        $("#pagenav").empty();
        var ul = $("<ul></ul>").addClass("pagination")
        var first = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
        first.click(function () {
            topage(1);
        });
        var pre = $("<li></li>").append($("<a></a>").append("&laquo;"));
        pre.click(function () {
            topage(data.extend.pageemps.pageNum - 1);
        });
        if (data.extend.pageemps.hasPreviousPage == false) {
            first.addClass("disabled");
            pre.addClass("disabled");
        }
        var next = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var last = $("<li></li>").append($("<a></a>").append("尾页").attr("href", "#"));
        next.click(function () {
            topage(data.extend.pageemps.pageNum + 1);
        });
        last.click(function () {
            topage(data.extend.pageemps.pages);
        });
        if (data.extend.pageemps.hasNextPage == false) {
            next.addClass("disabled");
            last.addClass("disabled");
        }
        ul.append(first)
            .append(pre);
        $.each(data.extend.pageemps.navigatepageNums, function (index, item) {
            var nums = $("<li></li>").append($("<a></a>").append(item));
            if (data.extend.pageemps.pageNum == item) {
                nums.addClass("active");
            }
            nums.click(function () {
                topage(item);
            });
            ul.append(nums);
        })
        ul.append(next)
            .append(last);

        var nav = $("<nav></nav>").append(ul)
        nav.appendTo("#pagenav");
    }

    function topage(pn) {
        $.ajax({
            url: "${root}/emps",
            data: "pn=" + pn,
            type: "GET",
            success: function (data) {
                buildtable(data);
                buildpageinfo(data);
                buildpagenav(data);
            }
        });
    }

    $("#insert").click(function () {
        $('#insertemp').on('hidden.bs.modal', function () {
            document.getElementById("insertemps").reset();
            $("#insertemp").find("*").removeClass("has-error has-success");
            $("#insertemp").find(".help-block").text("");
        });
        $("#dep").empty();
        var name = "";
        name = $("#inputname").val()
        $.ajax({
            url: "${root}/getdep",
            type: "GET",
            success: function (data) {
                $.each(data.extend.dep, function (index, item) {
                    var op = $("<option></option>").append(item.depname).attr("value", item.depid);
                    op.appendTo("#dep");
                })
            }
        });
        $('#insertemp').modal({
            backdrop: "static"
        });
    });

    function validata() {
        var name = $("#inputname").val();
        var email = $("#inputemail").val();
        var regexname = /(^[a-zA-Z0-9_-]{3,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        var regexemail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regexname.test(name)) {
            showcheckmsg("#inputname", "error", "请输入正确的用户名(3-16位英文字母或者2-5中文)！");
            return false;
        } else {
            showcheckmsg("#inputname", "success", "")
        }
        if (!regexemail.test(email)) {
            showcheckmsg("#inputemail", "error", "请输入正确的邮箱！");
            return false;
        } else {
            showcheckmsg("#inputemail", "success", "")
        }
        return true;
    }

    function showcheckmsg(ele, status, msg) {
        //清除样式
        $(ele).parents().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if (status == "success") {
            $(ele).parents().addClass("has-success");
            $(ele).next("span").text(msg);
        } else {
            $(ele).parents().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }

    $("#inputname").change(function () {
        var username = $("#inputname").val();
        $.ajax({
            url: "${root}/checkname",
            type: "POST",
            data: "name=" + username,
            success: function (data) {
                if (data.code == 100) {
                    showcheckmsg("#inputname", "success", "用户名可用");
                    $("#save").attr("ajax-va", "success");
                } else {
                    showcheckmsg("#inputname", "error", data.extend.va_name);
                    $("#save").attr("ajax-va", "error");
                }
            }
        })
    })


    $("#save").click(function () {
        if (!validata()) {
            return;
        }
        if ($("#save").attr("ajax-va") == "error") {
            return false;
        }
        $.ajax({
            url: "${root}/savedep",
            type: "POST",
            data: $("#insertemp form").serialize(),
            success: function (data) {
                if (data.code == 100) {
                    //$('#error').modal('show')
                    //清除模态框中的表单信息
                    $('#insertemp').on('hidden.bs.modal', function () {
                        document.getElementById("insertemps").reset();
                    });
                    //清除模态框中的表单信息
                    $('#insertemp').modal('hide');
                    topage(total + 2);
                } else {
                    //$('#error').modal('show');
                    //console.log(data);
                    if (undefined != data.extend.errorFields.email) {
                        showcheckmsg("#inputemail", "error", data.extend.errorFields.email);
                    }
                    if (undefined != data.extend.errorFields.name) {
                        showcheckmsg("#inputname", "error", data.extend.errorFields.name)
                    }
                }
            }
        });
    });


    $(document).on("click", ".editbtn", function () {
        $("#editdep").empty();
        id = $(this).attr("value");
        //获取部门
        $.ajax({
            url: "${root}/getdep",
            type: "GET",
            success: function (data) {
                $.each(data.extend.dep, function (index, item) {
                    var op = $("<option></option>").append(item.depname).attr("value", item.depid);
                    op.appendTo("#editdep");
                })
            }
        });

        //获取信息
        $.ajax({
            url: "${root}/emps/" + id,
            type: "GET",
            success: function (data) {
                var editempdata = data.extend.emp;
                $("#editname").text(editempdata.name);
                name = editempdata.name;
                $("#editemail").val(editempdata.email);
                $("#edit input[name=gender]").val([editempdata.gender]);
                $("#edit select").val([editempdata.idtodepid]);
            }
        });
        $("#edit").modal({
            backdrop: "static"
        })
    })


    //更新
    $("#editsave").click(function () {
        var email = $("#editemail").val();
        var regexemail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regexemail.test(email)) {
            showcheckmsg("#editemail", "error", "请输入正确的邮箱！");
            return false;
        } else {
            showcheckmsg("#editemail", "success", "")
        }
        $.ajax({
            url: "${root}/emps/" + id,
            type: "POST",
            data: $("#edit form").serialize() + "&_method=PUT",
            success: function (data) {
                if (data.code == 100) {
                    $('#edit').modal('hide');
                    topage(currentpage);
                } else {
                    alert("修改失败！");
                }
            }
        })

    })


    $(document).on("click", ".delbtn", function () {
        id = $(this).attr("value");
        var delname = $(this).parents("tr").find("td:eq(2)").text();
        if (confirm("确认删除?")) {
            $.ajax({
                url: "${root}/emps/" + id,
                type: "POST",
                data: "id=" + id + "&_method=DELETE",
                success: function (data) {
                    if (data.code == 100) {
                        $('#edit').modal('hide');
                        topage(currentpage);
                    } else {
                        alert("修改失败！");
                    }
                }
            })
        }
    })

    $("#checkall").click(function () {
        $(".checkitems").prop("checked", $(this).prop("checked"));
    })

    $(document).on("click", ".checkitems", function () {
        var flag;
        if ($(".checkitems:checked").length == $(".checkitems").length) {
            flag = true;
        } else {
            flag = false;
        }
        $("#checkall").prop("checked", flag);

    })

    $("#delall").click(function () {
        var ids = "";
        $.each($(".checkitems:checked"), function (index, item) {
            if (index < $(".checkitems:checked").length - 1) {
                ids += $(this).parents("tr").find("td:eq(1)").text() + ",";
            } else {
                ids += $(this).parents("tr").find("td:eq(1)").text();
            }
        })
        $.ajax({
            url: "${root}/emps/" + ids,
            type: "POST",
            data: "ids=" + ids,
            success: function (data) {
                if (data.code == 100) {
                    $('#edit').modal('hide');
                    topage(currentpage);
                } else {
                    alert("删除失败！");
                }
            }
        })
    })

</script>
</body>
</html>
